﻿namespace Blaze.Editor.EditorExtensions.ProjectComponents
{
    using System.IO;
    using Analysing;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 显示资源的引用计数。
    /// </summary>
    public class ReferenceCounter : ProjectComponent
    {
        /// <summary>
        /// 当需要绘制组件时调用此方法。
        /// </summary>
        protected override void OnDraw(string guid, Rect selectionRect)
        {
            GUI.Label(mRect, mContent, mGUIStyle);
        }

        /// <summary>
        /// 当需要初始化组件时调用此方法。
        /// </summary>
        protected override void OnInitialize()
        {
            base.OnInitialize();
            mGUIStyle = new GUIStyle("Hi Label") {normal = {textColor = Color.black}};
        }

        /// <summary>
        /// 当组件需要布局的时调用此方法。
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="rect">剩余可用的空间</param>
        protected override bool OnLayout(string guid, ref Rect rect)
        {
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            var extension = Path.GetExtension(assetPath);
            if (string.IsNullOrEmpty(extension))
                return false;
            var text = ReferenceAnalysor.GetReferenceCount(assetPath).ToString();
            mContent = new GUIContent(text);
            var size = mGUIStyle.CalcSize(mContent);

            mRect.width = size.x;
            mRect.x = rect.xMax - mRect.width;
            mRect.y = rect.y;
            rect = new Rect(rect)
            {
                width = rect.width - mRect.width,
            };
            return true;
        }

        /// <summary>
        /// 当需要验证组件是否显示时调用此方法。
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        protected override bool OnValidate(string guid)
        {
            return ReferenceAnalysor.Available;
        }

        private Rect mRect = new Rect(0, 0, 16, 16);
        private GUIContent mContent;
        private GUIStyle mGUIStyle;
    }
}